package com.itfreer.gis.map.style;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.alibaba.dubbo.config.annotation.Service;
import com.itfreer.data.config.ConfigVersionService;
import com.itfreer.form.api.BaseDao;
import com.itfreer.form.api.DataInputResult;
import com.itfreer.utils.SpringContext;
import com.itfreer.utils.file.FileMeta;
import com.itfreer.utils.file.FilePara;
import com.itfreer.gis.map.style.entity.MapStyleDirectoryEntity;
import com.itfreer.gis.map.style.dao.MapStyleDirectoryDao;
import com.itfreer.form.api.DictionaryServiceImp;
import com.itfreer.form.api.dictionary.DictionaryEntity;

/**
 * 定义我的样式目录实现类
 */
@Component
@Service(interfaceClass = MapStyleDirectoryService.class, path = "gismapstyledirectory")
public class MapStyleDirectoryServiceImp extends DictionaryServiceImp<MapStyleDirectoryEntity>
		implements MapStyleDirectoryService {

	@Autowired
	private MapStyleDirectoryDao dao;

	@Autowired
	private MapStyleService gisMapStyleDao;

	@Autowired(required = false)
	private ConfigVersionService configVersionService;

	@Override
	protected BaseDao<MapStyleDirectoryEntity> getDao() {
		return dao;
	}

	@Override
	public String getDictionaryName() {
		return "p_style_directory";
	}

	@Override
	protected DictionaryEntity convert(MapStyleDirectoryEntity entity) {
		DictionaryEntity toEntity = new DictionaryEntity();
		BeanUtils.copyProperties(entity, toEntity);
		toEntity.setDisplay(entity.getName());
		toEntity.setCode(entity.getId());
		toEntity.setId(entity.getId());
		toEntity.setOrder(entity.getOrder());
		toEntity.setTenantID(entity.getTenantID());
		toEntity.setTenantName(entity.getTenantName());
		toEntity.getOther().put("info", entity.getInfo());
		toEntity.getOther().put("recommend", entity.getRecommend());
		toEntity.getOther().put("image", entity.getImage());
		toEntity.setLeaf(true);
		return toEntity;
	}

	@Override
	protected String getDictionaryFields() {
		return "*";
	}

	@Override
	public Boolean delete(String id) {
		// 配置事务策略
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setName("planOne-transaction");
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置状态点
		TransactionStatus status = transactionManager.getTransaction(def);
		Boolean result = false;
		try {
			result = super.delete(id);
			// 方案详情
			Map<String, Object> where = new HashMap<String, Object>();
			where.put("styleId", id);
			gisMapStyleDao.deletes(where);
			configVersionService.addVersion();
		} catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
		transactionManager.commit(status);
		return result;
	}

	/**
	 * 添加实体
	 * 
	 * @param entity
	 *            添加实体
	 * @return
	 */
	@Override
	public MapStyleDirectoryEntity add(MapStyleDirectoryEntity entity) {
		configVersionService.addVersion();
		return super.add(entity);
	}

	/**
	 * 更新实体
	 * 
	 * @param guid
	 *            唯一值
	 * @param entity
	 *            实体
	 * @return
	 */
	@Override
	public MapStyleDirectoryEntity update(MapStyleDirectoryEntity entity) {
		configVersionService.addVersion();
		return super.update(entity);
	}

	/**
	 * 指量删除实体
	 * 
	 * @param guid
	 *            唯一值集
	 */
	@Override
	public Boolean deletes(String guids) {
		configVersionService.addVersion();
		return super.deletes(guids);
	}

	/**
	 * 逻辑删除恢复
	 * 
	 * @param guid
	 */
	@Override
	public Boolean reply(String guid) {
		configVersionService.addVersion();
		return super.reply(guid);
	}

	/**
	 * 导入Excel数据
	 * 
	 * @return
	 */
	@Override
	public DataInputResult input(String fileName, InputStream fileStream, String inputID, Integer startrow) {
		configVersionService.addVersion();
		return super.input(fileName, fileStream, inputID, startrow);
	}

	/**
	 * 导入Shape数据
	 * 
	 * @param fileNmae
	 *            文件名
	 * @return
	 */
	@Override
	public DataInputResult importShape(String fileName, String inputID) {
		configVersionService.addVersion();
		return super.importShape(fileName, inputID);
	}

	/**
	 * 获取推荐方案
	 */
	public List<StyleInfo> recommend() {
		List<StyleInfo> result = innerRecommend(new CustomOwerFilter());
		if (result == null || result.size() <= 0) {
			result = innerRecommend(new CustomTenantFilter());
		}
		return result;
	}

	private List<StyleInfo> innerRecommend(CustomFilter customFilter) {
		List<StyleInfo> result = new ArrayList<>();
		List<DictionaryEntity> caches = this.dictionaryService.getAll(this.getDictionaryName(), false);
		FilePara filePara = SpringContext.getBean(FilePara.class);
		for (DictionaryEntity item : caches) {
			DictionaryEntity entity = customFilter.filter(item);
			if (entity == null) {
				continue;
			}
			Object recommend = entity.getOther().get("recommend");
			if (recommend != null && recommend.equals(true)) {
				StyleInfo pInfo = new StyleInfo();
				pInfo.setId(entity.getId());
				pInfo.setName(entity.getDisplay());
				Object image = entity.getOther().get("image");
				if (image != null) {
					FileMeta[] images = (FileMeta[]) image;
					if (images.length > 0) {
						FileMeta fileMeta = images[0];
						if (filePara != null) {
							pInfo.setImage(filePara.getDownloadUrl(fileMeta));
						} else {
							pInfo.setImage("");
						}
					} else {
						pInfo.setImage("");
					}
				} else {
					pInfo.setImage("");
				}
				pInfo.setOrder(entity.getOrder());
				result.add(pInfo);
			}
		}
		return result;
	}

	interface CustomFilter {
		DictionaryEntity filter(DictionaryEntity item);
	}

	class CustomTenantFilter implements CustomFilter {

		@Override
		public DictionaryEntity filter(DictionaryEntity item) {
			if (tenantPower.getTenantID() == null || item.getTenantID() == null) {
				return item;
			}
			if (item.getTenantID().equals("-1")) {
				return item;
			} else {
				return null;
			}
		}

	}

	class CustomOwerFilter implements CustomFilter {

		@Override
		public DictionaryEntity filter(DictionaryEntity item) {
			if (tenantPower.getTenantID() == null || item.getTenantID() == null) {
				return item;
			}
			if (tenantPower.getTenantID().equals(item.getTenantID())) {
				return item;
			} else {
				return null;
			}
		}

	}
}
